package com.totoro.tymapping.manager;

import com.totoro.tymapping.TyMapping;
import com.totoro.tymapping.bo.CheckParseBo;
import com.totoro.tymapping.constants.StaticSystemVarConst;
import com.totoro.tymapping.task.AttrPotionEffectTask;
import com.totoro.tymapping.task.CheckParseTask;
import com.totoro.tymapping.utils.ColorUtil;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Totoro
 * @version 0.1.0
 * @date 2025/8/13 - 2:55
 * @description 检测任务管理器
 **/
public class CheckTaskManager {

    private final TyMapping plugin;
    /* 存放所有玩家解析后的属性和药水给予 */
    private final Map<UUID, CheckParseBo> playerCheckParseBoMap = new ConcurrentHashMap<>();
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    private CheckParseTask asyncTask;
    private AttrPotionEffectTask mainTask;

    public CheckTaskManager(TyMapping plugin) {
        this.plugin = plugin;
        start();
    }

    /***
     * @author totoro
     * @description 启动检测任务
     * @date  14:39
     * @param
     * @return void
     **/
    public void start() {
        if(isRunning.compareAndSet(false, true)) {
            // 解析玩家条件和给予内容
            asyncTask = new CheckParseTask(plugin);
            mainTask = new AttrPotionEffectTask(plugin);
            asyncTask.runTaskTimerAsynchronously(plugin, 0, 40L);
            mainTask.runTaskTimer(plugin, 0, 40L);
            plugin.getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX +
                    ColorUtil.color("&e检测任务已启动！"));
        }
    }
    
    /**
     * @author totoro
     * @description 关闭检测任务
     * @date  17:33
     * @param []
     * @return void
     **/
    public void stop() {
        if(isRunning.compareAndSet(true, false)) {
            asyncTask.cancel();
            mainTask.cancel();
            plugin.getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX +
                    ColorUtil.color("&c检测任务已关闭！"));
        }
    }


    public void put(UUID uuid, CheckParseBo checkParseBo) {
        playerCheckParseBoMap.put(uuid, checkParseBo);
    }

    public void remove(UUID uuid) {
        playerCheckParseBoMap.remove(uuid);
    }

    public Map<UUID, CheckParseBo> getPlayerCheckParseBoMap() {
        return Collections.unmodifiableMap(playerCheckParseBoMap);
    }
}
